package com.jisf.driver.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jisf.driver.auth.MyPasswordEncoder;
import com.jisf.driver.entity.dto.UserChatDto;
import com.jisf.driver.entity.dto.UserListRequestDto;
import com.jisf.driver.entity.enumtype.*;
import com.jisf.driver.entity.po.User;
import com.jisf.driver.entity.vo.*;
import com.jisf.driver.exception.DrivingSchoolException;
import com.jisf.driver.exception.SystemException;
import com.jisf.driver.mapper.UserMapper;
import com.jisf.driver.response.IErrorCode;
import com.jisf.driver.response.ResultCode;
import com.jisf.driver.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jisf.driver.utils.DateUtil;
import com.jisf.driver.utils.UUIDUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author jisf
 * @since 2022-04-08
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private MyPasswordEncoder myPasswordEncoder;

    /**
     * 获取用户列表
     * @param userListRequestVo
     * @return
     */
    @Override
    public UserListResponseVo pageUserList(UserListRequestVo userListRequestVo) {
        try {
            UserListRequestDto userListRequestDto = new UserListRequestDto();
            Page<User> page = new Page<>(userListRequestVo.getPage(), userListRequestVo.getSize());
            BeanUtils.copyProperties(userListRequestVo, userListRequestDto);
            String status = userListRequestVo.getStatus();
            if (StringUtils.isNotBlank(status)) {
                userListRequestDto.setStatus(StatusEnum.getEnum(status));
            }

            List<UserListVo> userListVos = userMapper.selectUsers(userListRequestDto, page);
            long total = page.getTotal();
            UserListResponseVo userList = new UserListResponseVo(total, userListVos);
            return userList;
        } catch (Exception e) {
            throw new SystemException(e);
        }
    }

    /**
     * 改变用户状态
     * @param id
     * @param status
     * @return
     */
    @Override
    public IErrorCode userChangeStatus(Integer id, String status) {
        try {
            UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
            updateWrapper.set("status", StatusEnum.getEnum(status));
            updateWrapper.eq("id", id);
            int update = userMapper.update(new User(), updateWrapper);
            return update == 0 ? ResultCode.USER_STATUS_UPDATE_FAILED : ResultCode.USER_STATUS_UPDATE_SUCCESS;
        } catch (Exception e) {
            throw new SystemException(e);
        }
    }

    /**
     * 添加用户
     * @param userAddRequestVo
     * @return
     */
    @Override
    public IErrorCode userAdd(UserAddRequestVo userAddRequestVo) {
        try {
            User user = new User();
            BeanUtils.copyProperties(userAddRequestVo, user);
            user.setPassword(myPasswordEncoder.encode(user.getPassword()));
            // 检验username是否存在
            if (checkUsername(user.getUsername())) {
                throw new DrivingSchoolException("用户名已存在");
            }

            String status = userAddRequestVo.getStatus();
            if (StringUtils.isNotBlank(status)) {
                user.setStatus(StatusEnum.getEnum(status));
            } else {
                user.setStatus(StatusEnum.UNABLE);
            }
            user.setDelFlag(DelFlagEnum.NO_DELETE);
            String sex = userAddRequestVo.getSex();
            if (StringUtils.isNotBlank(sex)) {
                user.setSex(SexEnum.getEnum(status));
            }
            String nationality = userAddRequestVo.getNationality();
            if (StringUtils.isNotBlank(nationality)) {
                user.setNationality(NationalityMenu.getEnum(status));
            }
            String dateOfBirth = userAddRequestVo.getDateOfBirth();
            if (StringUtils.isNotBlank(dateOfBirth)) {
                Date dateOfBirthDate = DateUtil.YearToDay.parse(dateOfBirth);
                user.setDateOfBirth(dateOfBirthDate);
            }
            int insert = userMapper.insert(user);
            return insert == 0 ? ResultCode.USER_ADD_FAILED : ResultCode.USER_ADD_SUCCESS;
        } catch (ParseException e) {
            throw new DrivingSchoolException("日期格式异常", e);
        } catch (DrivingSchoolException e) {
            throw new DrivingSchoolException(e.getMessage());
        } catch (Exception e) {
            throw new SystemException(e);
        }
    }

    /**
     * 删除用户
     * @param userid
     * @return
     */
    @Override
    public IErrorCode userDelete(Integer id) {
        try {
            UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("id", id);
            User user = new User();
            user.setDelFlag(DelFlagEnum.HAVE_DELETE);
            int update = userMapper.update(user, updateWrapper);
            return update == 0 ? ResultCode.USER_DEL_FLAG_FAILED : ResultCode.USER_DEL_FLAG_SUCCESS;
        }catch (Exception e){
            throw new SystemException(e);
        }
    }

    /**
     * 检验username是否已经存在，true：存在
     * @param username
     * @return
     */
    private boolean checkUsername(String username) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("username").eq("username", username);
        User user = userMapper.selectOne(queryWrapper);
        return user != null;
    }

    /**
     * 修改用户密码
     * @param userUpdatePasswordRequestVo
     * @return
     */
    @Override
    public IErrorCode updatePassword(UserUpdatePasswordRequestVo userUpdatePasswordRequestVo) {
        try {
            UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
            updateWrapper.set("password", myPasswordEncoder.encode(userUpdatePasswordRequestVo.getPassword()));
            updateWrapper.eq("id", userUpdatePasswordRequestVo.getId());
            int update = userMapper.update(null, updateWrapper);
            return update == 0 ? ResultCode.USER_PASSWORD_UPDATE_FAILED : ResultCode.USER_PASSWORD_UPDATE_SUCCESS;
        }catch (Exception e){
            throw new SystemException(e);
        }
    }

    /**
     * 获取聊天的用户
     * @param roleId
     * @return
     */
    @Override
    public List<UserChatDto> getUserChat(Integer roleId) {
        try {
            List<UserChatDto> userChat = userMapper.getUserChat(roleId);
            return userChat;
        }catch (Exception e){
            throw new SystemException(e);
        }
    }
}
